<script setup lang="ts">
import { FormInstance, FormRules } from 'element-plus';
import { onMounted, ref } from 'vue';
import { createNonEmptyRule, ModalForm, request, statusSelect, treeUtils } from '../../../utils';

type Fields = {
  _id?: any,
  parentId?: any | any[],
  deptName?: string,
  deptSort?: number,
  leader?: string,
  phone?: string,
  email?: string,
  status?: boolean
}

const props = defineProps<{ row?: Fields, isEdit?: boolean }>()

const form = ref<Fields>({})
const formRef = ref<FormInstance>()
const deptTree = ref<any>([])

const rules: FormRules<Fields> = {
  deptName: createNonEmptyRule('部门名称不能为空')
}

onMounted(async () => {
  const { row, isEdit } = props
  if (row) {
    form.value = isEdit ? { ...row } : { parentId: row._id, status: true }
  } else {
    form.value = { status: true }
  }
  const { data }: { data: any[] } = await request('/dept/options')
  if (isEdit) {
    const index = data.findIndex(_ => _._id === row?._id)
    if (index > -1) {
      data.splice(index, 1)
    } else {
      const flatArr = treeUtils.flat({ data })
      for (const item of flatArr) {
        const childs: any[] | undefined = item.children
        if (childs) {
          const index = childs.findIndex(_ => _._id === row?._id)
          if (index > -1) {
            childs.splice(index, 1)
          }
        }
      }
    }
  }
  deptTree.value = data
})

defineExpose<ModalForm>({
  validate () {
    return formRef.value?.validate()
  },
  submit () {
    return request.post(`/dept/${props.isEdit ? 'update' : 'add'}`, form.value)
  }
})
</script>

<template>
  <ElForm ref="formRef" label-width="6em" :model="form" :rules="rules">
    <ElFormItem label="上级部门">
      <ElCascader
        :style="{ width: '100%' }"
        :options="deptTree"
        filterable
        clearable
        :props="{ value: '_id', label: 'deptName', checkStrictly: true, emitPath: false }"
        v-model="form.parentId" />
    </ElFormItem>
    <ElFormItem label="部门名称" prop="deptName">
      <ElInput :maxlength="30" v-model="form.deptName" />
    </ElFormItem>
    <ElFormItem label="显示排序">
      <ElInputNumber controls-position="right" :min="1" :max="9999" v-model="form.deptSort" />
    </ElFormItem>
    <ElFormItem label="负责人">
      <ElInput :maxlength="20" v-model="form.leader" />
    </ElFormItem>
    <ElFormItem label="联系电话">
      <ElInput :maxlength="11" v-model="form.phone" />
    </ElFormItem>
    <ElFormItem label="邮箱">
      <ElInput :maxlength="50" v-model="form.email"/>
    </ElFormItem>
    <ElFormItem label="部门状态">
      <ElRadioGroup v-model="form.status">
        <ElRadio v-for="_ in statusSelect" :value="_.value">{{ _.label }}</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
  </ElForm>
</template>
